<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2018/2/28
 * Time: 15:34
 */

namespace app\business;
use app\business\BaseBusiness;
use app\libs\HxSms;
use app\libs\Predis;
use app\libs\SendSms;
use think\Config;

class Mobile extends BaseBusiness
{
    const KEY_SMS = 'qc_sms';

    public $redis = null;

    public function __construct()
    {
        $this->redis = new Predis();
    }
    public function sendSms($data){
        // 如果发过了需要一分钟后再发
        $key_time = self::KEY_SMS.':type:'.$data['type'].':mobile:'.$data['mobile'].':time';
        $ttl = $this->redis->get($key_time);

        if ($ttl){
            $this->result['status'] = -1;
            $this->result['msg'] = '验证码已发送请勿频繁请求';
            //return $this->result;
        }
        $smsObj = new HxSms();
        $sms_code = $this->getSms($data['type'],$data['mobile']);

        if ($sms_code){
            $value = $sms_code;
        }else{
            // 过期了
            $value = rand(1000,9999);
        }
        $sms_result = $smsObj ->send($data['mobile'],$value);
        $sms_result=json_decode($sms_result,true);
        if ($sms_result['returnstatus'] !== 'Success'){
           $this->result['status'] = -1;
           $this->result['msg'] = $sms_result['message'];
           return $this->result;
        }
        // 计入缓存
        $key = self::KEY_SMS.':type:'.$data['type'].':mobile:'.$data['mobile'];
        $key_time = self::KEY_SMS.':type:'.$data['type'].':mobile:'.$data['mobile'].':time';
        $this->redis->set($key_time,1,config('app.mobile_code.left_time'));
        $this->redis->set($key,$value,config('app.mobile_code.exp_time'));

        $this->result['status'] = 1;
        $this->result['msg'] = '发送成功';
        $this->result['data'] ['code'] = $value;

        return $this->result;
    }
    public function getSms($type,$mobile){
        $key = self::KEY_SMS.':type:'.$type.':mobile:'.$mobile;
        $sms = $this->redis->get($key);
        if(!$sms){
            return false;
        }
        return $sms;
    }

    public function checkmobileCode($mobile,$code,$type){
        $key_time = $key = self::KEY_SMS.':type:'.$type.':mobile:'.$mobile. ':time';
        $time = (int)$this->redis->get($key_time);
        if ($time>3){
            // 清楚code
            $this->delSms($type,$mobile);
            return 2;
        }

        $key = self::KEY_SMS.':type:'.$type.':mobile:'.$mobile;
        $sms = $this->redis->get($key);
        if (!$sms){
            return false;
        }
        if ($sms != $code){
            $new_time = $time + 1;
            $this->redis->set($key_time,$new_time,config('app.mobile_code.error_time'));
            return false;
        }
        return true;
    }

    public function delSms($type,$mobile){
        $key = self::KEY_SMS.':type:'.$type.':mobile:'.$mobile;
        $this->redis->del($key);
    }

    public function sendmobileSms($user_no,$token_password,$reqData){
        //查询该用户是否已设置手机
        $filed = ['mobile'];
        $userInfo = $this->getBusiness('RedisCache')->getUserInfo($user_no,$token_password,$filed);
        if(!$userInfo){
            $this->result['status'] = -1;
            $this->result['msg'] = 'login_expire';
            return $this->result;
        }

        if($reqData['type'] == 1){
            if($userInfo['mobile'] != ''){
                $this->result['status'] = -1;
                $this->result['msg'] = 'mobile_exit';
                return $this->result;
            }
        }elseif($reqData['type'] == 2){
            if($userInfo['mobile'] == ''){
                $this->result['status'] = -1;
                $this->result['msg'] = 'mobile_not_exit';
                return $this->result;
            }
        }else{
            $this->result['status'] = -1;
            $this->result['msg'] = 'mobile_type_error';
            return $this->result;
        }

        if($reqData['type'] == 2){
            //解绑
            //根据user_no查询手机号
            $reqData['mobile'] = $userInfo['mobile'];
        }elseif($reqData['type'] == 1){
            //判断手机号的唯一性
            $mobile = $this->getBusiness('User')->getBymobile($reqData['mobile']);
            if($mobile){
                $this->result['status'] = -1;
                $this->result['msg'] = 'mobile_exit_uno';
                return $this->result;
            }
        }


        //redis查询该手机号码的验证码是否还有有效值
        $sms = $this->getSms($user_no,$reqData['type'],$reqData['mobile']);
        if(!$sms){
            $sms_code = mt_rand(100000,999999);
        }else{
            $sms_code = $sms;
        }

        //将短信数据存储到redis 和 数据库
        $sendSmsData['user_no'] = $user_no;
        $sendSmsData['mobile'] = $reqData['mobile'];
        $sendSmsData['code'] = $sms_code;
        $sendSmsData['type'] = $reqData['type'];
        $sendSms = $this->getModel('Mobile')->saveMobile($sendSmsData);
        if(!$sendSms){
            $this->result['status'] = -1;
            $this->result['msg'] = 'send_sms_fail';
            return $this->result;
        }

        //发送短信（存储redis）
        $this->sendSms($user_no,$reqData['type'],$reqData['mobile'],$sms_code);

        //根据header获取语言
        $lang = $this->request->getHeader('lang');

        //发送短息（sendsms）
        $this->sendmobile($reqData['mobile'],$lang,'code',$sms_code);

        $this->result['status'] = 1;
        $this->result['msg'] = 'send_sms_success';
        return $this->result;
    }

    public function checkmobileSms($user_no,$token_password,$reqData){
        if($reqData['type'] == 2){
            //解绑
            //根据user_no查询手机号
            $filed = ['mobile'];
            $user = $this->getBusiness('RedisCache')->getUserInfo($user_no,$token_password,$filed);
            $reqData['mobile'] = $user['mobile'];
        }elseif($reqData['type'] == 1){
            //判断手机号的唯一性
            $mobile = $this->getBusiness('User')->getBymobile($reqData['mobile']);
            if($mobile){
                $this->result['status'] = -1;
                $this->result['msg'] = 'mobile_exit_uno';
                return $this->result;
            }
        }

        //判断验证码是否正确(true:正确 false：失败 2：次数过多)
        $checkmobile = $this->checkSms($user_no,$reqData['type'],$reqData['mobile'],$reqData['code']);
        if(!$checkmobile){
            $this->result['status'] = -1;
            $this->result['msg'] = 'sms_code_error';
            return $this->result;
        }

        if($checkmobile === 2){
            $this->result['status'] = -1;
            $this->result['msg'] = 'sms_code_time_more';
            return $this->result;
        }

        //同步数据库 和 redis
        if($reqData['type'] == 1){
            //绑定
            $data['mobile'] = $reqData['mobile'];
            $addmobile = $this->getBusiness('User')->updateByUserNo($user_no,$data);
            if(!$addmobile){
                $this->result['status'] = -1;
                $this->result['msg'] = 'add_mobile_fail';
                return $this->result;
            }

            $this->getBusiness('RedisCache')->setUserInfo($user_no,$token_password,$data);

            $msg = 'add_mobile_success';
        }elseif($reqData['type'] == 2){
            //解绑
            $data['mobile'] = '';
            $addmobile = $this->getBusiness('User')->updateByUserNo($user_no,$data);
            if(!$addmobile){
                $this->result['status'] = -1;
                $this->result['msg'] = 'del_mobile_fail';
                return $this->result;
            }

            $this->getBusiness('RedisCache')->setUserInfo($user_no,$token_password,$data);

            $msg = 'del_mobile_success';
        }else{
            $this->result['status'] = -1;
            $this->result['msg'] = 'mobile_type_error';
            return $this->result;
        }

        $this->delSms($reqData['type'],$reqData['mobile']);

        $this->result['status'] = 1;
        $this->result['msg'] = $msg;
        return $this->result;
    }


    //mobile:手机 lang：语言 param：状态 code：信息
    public function sendmobile($data){
        //判断语言
        if($lang == 'zh-CN'){
            $language = 'cn';
        }else{
            $language = 'en';
        }

        //判断是否是国籍手机
        $mobileLenth = strlen($mobile);
        if($mobileLenth < 11){
            $area = 'english';
        }else{
            $area = 'china';
        }

        $sms = [];
        $templateId = [];
        switch ($param){
            case 'login':
                $templateId['china']['cn'] = '14574';
                $templateId['china']['en'] = '15368';
                $templateId['english']['cn'] = '15455';
                $templateId['english']['en'] = '15460';
                break;
            case 'code':
                $templateId['china']['cn'] = '14733';
                $templateId['china']['en'] = '15437';
                $templateId['english']['cn'] = '15459';
                $templateId['english']['en'] = '15464';
                break;
        }

        $sms['templateId'] = $templateId[$area][$language];
        $sms['mobile'] = $mobile;
        $sms['code'] = $code;
        $SendSms = new SendSms();
        $SendSms->send_sms($sms);
    }
}